import dayjs from 'dayjs';
import { Platform } from 'react-native';

export const waiting = (ms = 0) => (
  new Promise(resolve => setTimeout(resolve, ms))
);

// 16进制颜色转 rgba
export function hexToRgba(hexColor: string, alpha = 1) {
  const hex = hexColor.replace('#', '');
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

export const isIos = () => Platform.OS === 'ios';


// 格式化时间
export const formatDate = (date: number | string, fromNow = true) => {
  const d = dayjs(date);
  let result = d.format('MMM DD HH:mm');
  if (!fromNow) return result;

  const now = dayjs();
  const hours = Math.abs(d.diff(now, 'hour'));
  const seconds = Math.abs(d.diff(now, 'second'));
  const minutes = Math.abs(d.diff(now, 'minute'));

  // 大于24小时，显示正常的时分秒
  if (hours >= 24) {
    // 不是同一年, 需要显示年份
    if (!now.isSame(d, 'year')) {
      result = d.format('MMM DD, YYYY HH:mm');
    }
  } else {
    // 小于1小时
    if (hours < 1) {
      // 小于1分钟
      result = minutes < 1 ?
        `${seconds}s ago` :
        `${minutes}min ago`;
    } else {
      result = `${hours}h ago`;
    }
  }
  return result;
};